package com.mifengs.mall.mqtt;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.mifengs.commonbase.util.DeviceInfoUtil;
import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.entity.DeliveryPushBean;
import com.mifengs.mall.entity.MqttMsg;
import com.mifengs.mall.event.MainEvent;
import com.mifengs.mall.event.PushMsgEvent;
import com.mifengs.mall.event.WebFrgEvent;
import com.mifengs.mall.ui.push.PushDialogActivity;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.Date;

import static java.lang.Thread.sleep;

/**
 * Created by lihaoqi on 2018/1/24.
 */

public class MqttRecvUtil {


    public static void Recv(){
        final String broker;
        final String topic;
        final String clientId;
        boolean islogin = PreferenceUtils.getLoginStatus();
        String phone = "";
        if(islogin){
            phone = PreferenceUtils.getUserMobile(MallApplication.getInstance());
        }
        String  date = new Date().getTime()+"";
        if(Constant.MQ_CONFIG){
             topic ="pro_pushphone";
             broker ="tcp://post-cn-mp90gliqs0n.mqtt.aliyuncs.com";
            if(!TextUtils.isEmpty(phone)){
              clientId ="GID_pushphone@@@MIFENG_"+phone;
            }else{
                String deviceId = DeviceInfoUtil.getDeviceId(MallApplication.getInstance());
                clientId ="GID_pushphone@@@MIFENG_"+ deviceId;
            }

          }else{
              broker ="tcp://mqtt-cn-4590g8k7e06.mqtt.aliyuncs.com"; //test
              topic ="test_maopao";//test
            if(!TextUtils.isEmpty(phone)){
                clientId ="GID_test_maopao@@@MIFENG_"+phone;//test
            }else{
                String deviceId = DeviceInfoUtil.getDeviceId(MallApplication.getInstance());
                clientId ="GID_test_maopao@@@MIFENG_"+deviceId;//test
            }
          }


        /**
         * 设置阿里云的AccessKey，用于鉴权
         */
        final String acessKey ="LTAIb7uT0uZ0dZtk";
        /**
         * 设置阿里云的SecretKey，用于鉴权
         */
        final String secretKey ="Jk4rQh049u1tyl1N5cGPuu7W6Tg6Eb";
        /**
         * 发消息使用的一级Topic，需要先在MQ控制台里申请
         */
        /**
         * MQTT的ClientID，一般由两部分组成，GroupID@@@DeviceID
         * 其中GroupID在MQ控制台里申请
         * DeviceID由应用方设置，可能是设备编号等，需要唯一，否则服务端拒绝重复的ClientID连接
         */


        LogUtil.i("mqtt_mfsc:",clientId);
        String sign;
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            final MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            final MqttConnectOptions connOpts = new MqttConnectOptions();
            System.out.println("Connecting to broker: " + broker);
            /**
             * 计算签名，将签名作为MQTT的password
             * 签名的计算方法，参考工具类MacSignature，第一个参数是ClientID的前半部分，即GroupID
             * 第二个参数阿里云的SecretKey
             */
            sign = MacSignature.macSignature(clientId.split("@@@")[0], secretKey);
            /**
             * 设置订阅方订阅的Topic集合，此处遵循MQTT的订阅规则，可以是一级Topic，二级Topic，P2P消息请订阅/p2p
             */
            final String[] topicFilters=new String[]{topic,topic+"/maopao"};
            final int[]qos={0,0};
            connOpts.setUserName(acessKey);
            connOpts.setServerURIs(new String[] { broker });
            connOpts.setPassword(sign.toCharArray());
            connOpts.setCleanSession(true);
            connOpts.setKeepAliveInterval(10);
            connOpts.setAutomaticReconnect(true);
            sampleClient.setCallback(new MqttCallbackExtended() {
                public void connectComplete(boolean reconnect, String serverURI) {
                    //System.out.println("connect success");
                    LogUtil.i("mqtt_mfsc:","connect success");
                    //连接成功，需要上传客户端所有的订阅关系
                    EventBus.getDefault().post(new MainEvent(MainEvent.APPLAUNCH));
                    try {
                        sampleClient.subscribe(topicFilters,qos);
                    } catch (MqttException e) {
                        Log.e("mqtt_mfsc",e.getMessage());
                        e.printStackTrace();
                    }
                }
                public void connectionLost(Throwable throwable) {
                    String threadName =  Thread.currentThread().getName();
                    LogUtil.i("mqtt_mfsc:","线程名称:"+threadName);
                    LogUtil.i("mqtt_mfsc:","mqtt connection lost");
                   // System.out.println("mqtt connection lost");
                }
                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    String threadName =  Thread.currentThread().getName();
                    LogUtil.i("mqtt_mfsc:","线程名称:"+threadName);
                    LogUtil.i("mqtt_mfsc:","messageArrived:" + topic + "------" + new String(mqttMessage.getPayload()));
                    try {JSONObject obj = new JSONObject(mqttMessage.toString());
                        if (!obj.isNull("status")) {
                            if(mqttMessage !=null){
                                MqttMsg mqttMsg = new Gson().fromJson(mqttMessage.toString(),MqttMsg.class);
                                if(mqttMsg.getResults().getAlertType()!=null){
                                    if(mqttMsg.getResults().getAlertType().equals("02")){
                                        PushMsgEvent pushMsgEvent = new PushMsgEvent(PushMsgEvent.MOPAO_MSG);
                                        pushMsgEvent.setMqttMsg(mqttMsg);
                                        EventBus.getDefault().post(pushMsgEvent);
                                    }
                                }
                                if(mqttMsg.getResults().getType()!=null){
                                    if(mqttMsg.getResults().getType().equals("01")){
                                        Intent intent = new Intent(MallApplication.getInstance(), PushDialogActivity.class);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        intent.putExtra("mqttMessage",mqttMessage.toString());
                                        MallApplication.getInstance().startActivity(intent);
                                    }else if(mqttMsg.getResults().getType().equals("03")){
                                        DeliveryPushBean deliveryPushBean = new Gson().fromJson(mqttMsg.getResults().getMessage().toString(),DeliveryPushBean.class);
                                        WebFrgEvent webFrgEvent = new WebFrgEvent(WebFrgEvent.DELIVERY_PUSH);
                                        webFrgEvent.setDeliveryPushBean(deliveryPushBean);
                                        EventBus.getDefault().post(webFrgEvent);
                                        MainEvent mainEvent = new MainEvent(MainEvent.MYMESSAGE);
                                        mainEvent.setAmount(mqttMsg.getResults().getTotal());
                                        EventBus.getDefault().post(mainEvent);
                                    } else if(mqttMsg.getResults().getType().equals("04")) {
                                        PushMsgEvent pushMsgEvent = new PushMsgEvent(PushMsgEvent.VOICE_MSG);
                                        pushMsgEvent.setMqttMsg(mqttMsg);
                                        EventBus.getDefault().post(pushMsgEvent);

                                    }
                                }
                            }
                        }
                    }catch (Exception e){
                        LogUtil.i("mqtt_mfsc:",e.toString());
                    }

                            // System.out.println("messageArrived:" + topic + "------" + new String(mqttMessage.getPayload()));
                }
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    LogUtil.i("mqtt_mfsc:","deliveryComplete:" + iMqttDeliveryToken.getMessageId());
                    //System.out.println("deliveryComplete:" + iMqttDeliveryToken.getMessageId());
                }
            });
            //客户端每次上线都必须上传自己所有涉及的订阅关系，否则可能会导致消息接收延迟
            sampleClient.connect(connOpts);
            //每个客户端最多允许存在30个订阅关系，超出限制可能会丢弃导致收不到部分消息
            sampleClient.subscribe(topicFilters,qos);
            try {
                sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
                if(sampleClient!=null){
                    //sampleClient.unsubscribe(topicFilters,qos);
                    sampleClient.setCallback(null);
                    sampleClient.close();
                }
                e.printStackTrace();
            }
        } catch (Exception me) {
            me.printStackTrace();
            LogUtil.i("mqtt_mfsc:",me.toString());

        }
    }

    public static void offlineMsg() throws Exception {
        final String broker ="tcp://mqtt-cn-4590g8k7e06.mqtt.aliyuncs.com";
        /**
         * 设置阿里云的AccessKey，用于鉴权
         */
        final String acessKey ="LTAIb7uT0uZ0dZtk";
        /**
         * 设置阿里云的SecretKey，用于鉴权
         */
        final String secretKey ="Jk4rQh049u1tyl1N5cGPuu7W6Tg6Eb";
        /**
         * 发消息使用的一级Topic，需要先在MQ控制台里申请
         */
        final String topic ="test_pushphone";
        /**
         * MQTT的ClientID，一般由两部分组成，GroupID@@@DeviceID
         * 其中GroupID在MQ控制台里申请
         * DeviceID由应用方设置，可能是设备编号等，需要唯一，否则服务端拒绝重复的ClientID连接
         */
        final String clientId ="GID_mifeng@@@MIFENG_002";
        final String[] topicFilters=new String[]{topic+"/notice/",topic+"/p2p"};
        final int[]qos={0,0};
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            final MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            final MqttConnectOptions connOpts = new MqttConnectOptions();
            System.out.println("Connecting to broker: " + broker);
            connOpts.setServerURIs(new String[]{broker});
            connOpts.setCleanSession(false);
            connOpts.setAutomaticReconnect(true);
            /**
             * 客户端长链接需要设置心跳实际，建议100s 以下，超时，服务端会断开连接
             */
            connOpts.setKeepAliveInterval(20);
            sampleClient.setCallback(new MqttCallbackExtended() {
                public void connectComplete(boolean reconnect, String serverURI) {
                    LogUtil.i("mqtt_mfsc:"," offlineMsg connect success");
                    try {
                        sampleClient.subscribe(topicFilters, qos);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void connectionLost(Throwable throwable) {

                }

                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    System.out.println("recv Msg from " + topic);
                    LogUtil.i("mqtt_mfsc:","messageArrived:" + mqttMessage + "------" + mqttMessage.toString());
                }
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    System.out.println("deliveryComplete:" + iMqttDeliveryToken.getMessageId());
                }
            });
            sampleClient.connect(connOpts);
            JSONObject object = new JSONObject();
            object.put("maxPushNum", 20);
            object.put("pushOrder", "DESC");
            sampleClient.publish("$SYS/getOfflineMsg", new MqttMessage(object.toString().getBytes()));
            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
